<?php
/**
 *
 * User: chenjunliang@star-net.cn
 * Time: 2017/10/30 10:05
 */

namespace app\console\swooletask\logic;


use app\console\swoole\model\Inventory;
use app\console\swoole\model\InventoryRemain;
use app\index\model\PositionType;
use think\Db;
use think\Log;

class InitSchedule {
    /**
     * @param $data
     */
    public function initScheduleRemain($data) {
        if(!$data) {
            $ret = [
                'type'    => 'initScheduleRemain',
                'status'  => false,
                'message' => 'data is empty'
            ];
            $this->_log($ret);

            return false;
        }

        //根据库存状态添加数据，第一次插入的库存，在剩余表里面插入三个工日之后到第70天的数据，
        //非第一次插入的，在剩余表里面插入第70天的数据
        $remainInfo      = [];
        $inveRemainModel = new InventoryRemain();
        $inidArr         = [];
        $errorInidArr    = [];
        $potModel        = new PositionType();
        foreach($data as $value) {
            $slidenum = $potModel->getSlidenumByCorrelation($value['correlation']);
            //默认1
            if(!$slidenum) {
                //存储广告位不存在的库存id更新为3，今日不再插库存
                $errorInidArr[] = $value['in_id'];
                continue;
            }
            $inidArr[] = $value['in_id'];
            if($value['init_status'] == 0) {
                $workday = $this->_get3WorkDay();
                while(strtotime($workday) <= strtotime('+70 day')) {
                    $remainInfo[] = [
                        'inr_in_id'       => $value['in_id'],
                        'inr_usable_nums' => $slidenum,
                        'inr_date'        => $workday
                    ];
                    $workday      = date('Y-m-d', strtotime($workday) + 86400);

                }
            } else if($value['init_status'] == 1) {
                $lastday = $inveRemainModel->getLastDataDayByInid($value['in_id']);
                if($lastday) {
                    $day = strtotime($lastday) + 86400;
                } else {
                    $day = strtotime('+70 day');
                }

                while($day <= strtotime('+70 day')) {
                    $remainInfo[] = [
                        'inr_in_id'       => $value['in_id'],
                        'inr_usable_nums' => $slidenum,
                        'inr_date'        => date('Y-m-d', $day)
                    ];
                    $day += 86400;
                }

            }
        }

        /*需要更新的插库存的*/
        $inveModel = new Inventory();
        if($inidArr){
            Db::startTrans();
            $ret = $inveRemainModel->addData($remainInfo);
            if(!$ret) {
                Db::rollback();
                $ret = [
                    'type'    => 'initScheduleRemain',
                    'status'  => false,
                    'inid'    => $inidArr,
                    'message' => 'add remain fail'
                ];
                $this->_log($ret);

                return false;
            }
            //添加成功更新初始化记录
            $inInfo    = [
                'in_init_status' => 2
            ];
            $up        = $inveModel->updateByid($inInfo, $inidArr);
            if(!$up) {
                Db::rollback();
                $ret = [
                    'type'    => 'initScheduleRemain',
                    'status'  => false,
                    'inid'    => $inidArr,
                    'message' => 'update fail'
                ];
            } else {
                Db::commit();
                $ret = [
                    'type'    => 'initScheduleRemain',
                    'status'  => true,
                    'inid'    => $inidArr,
                    'message' => 'success'
                ];
            }
            $this->_log($ret);
        }
        /*广告位不存在的，库存id更新为3，今日不再插库存*/
        if($errorInidArr){
            $inInfo    = [
                'in_init_status' => 3
            ];
            $up        = $inveModel->updateByid($inInfo, $errorInidArr);
            if(!$up) {
                $ret = [
                    'type'    => 'init error inventory (no positiontype) ',
                    'status'  => false,
                    'inid'    => $errorInidArr,
                    'message' => 'update fail'
                ];
            } else {
                $ret = [
                    'type'    => 'init error inventory (no positiontype)',
                    'status'  => true,
                    'inid'    => $errorInidArr,
                    'message' => 'success'
                ];
            }
            $this->_log($ret);
        }
        return true;
    }


    /**
     * 获取3个工作日之后的日期
     * @return bool|string
     */
    private function _get3WorkDay() {
        $w = date('w', time());
        if(in_array($w, [
            0,
            1
        ])) {
            return date('Y-m-d', strtotime('+4 day'));
        } else if(in_array($w, [
            2,
            3,
            4,
            5
        ])) {
            return date('Y-m-d', strtotime('+6 day'));
        } else {
            return date('Y-m-d', strtotime('+5 day'));
        }
    }

    private function _log($log) {
        Log::record(json_encode(['swoole_server' => $log]), 'elk_more_info','init_schedule');
        //Log::save();
    }
}